package com.ysd.lis.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ysd.common.Result;
import com.ysd.common.exception.job.TaskException;
import com.ysd.constant.Constants;
import com.ysd.lis.controller.pub.BaseController;
import com.ysd.lis.dto.SysJobDto;
import com.ysd.lis.entity.SysJob;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysJobService;
import com.ysd.lis.util.CronUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 调度任务信息操作处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/monitor/job")
public class SysJobController extends BaseController {
    @Autowired
    private SysJobService jobService;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    /**
     * 查询定时任务列表
     */
    @GetMapping("/list")
    public Result list(SysJob sysJob) {
        LambdaQueryWrapper<SysJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(sysJob.getJobName()), SysJob::getJobName, sysJob.getJobName());
        queryWrapper.eq(StringUtils.isNotBlank(sysJob.getJobGroup()), SysJob::getJobGroup, sysJob.getJobGroup());
        queryWrapper.eq(StringUtils.isNotBlank(sysJob.getStatus()), SysJob::getStatus, sysJob.getStatus());
        queryWrapper.eq(StringUtils.isNotBlank(sysJob.getSystemId()),SysJob::getSystemId,sysJob.getSystemId());
        queryWrapper.eq(StringUtils.isNotBlank(sysJob.getModuleId()),SysJob::getModuleId,sysJob.getModuleId());
        queryWrapper.eq(SysJob::getDelFlag, 0);
        queryWrapper.orderByAsc(SysJob::getJobGroup);
        List<SysJob> list = jobService.list(queryWrapper);
        List<Map<String, Object>> groupList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("TASK_GROUP_NAME").getData();
        if(CollectionUtils.isNotEmpty(list)){
            for (SysJob itm : list) {
                if (StringUtils.isNotBlank(itm.getJobGroup()) && CollectionUtils.isNotEmpty(groupList)) {
                    groupList.stream().filter(a -> a.get("code").equals(itm.getJobGroup())).findFirst().ifPresent(stringObjectMap -> itm.setJobGroupName((String) stringObjectMap.get("name")));
                }
            }
        }
        return Result.succ(list);
    }


    /**
     * 获取定时任务详细信息
     */
    @GetMapping(value = "/{id}")
    public Result getInfo(@PathVariable("id") String id) {
        LambdaQueryWrapper<SysJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysJob::getDelFlag, 0);
        queryWrapper.eq(SysJob::getId, id);

        return Result.succ(jobService.list(queryWrapper).get(0));
    }

    /**
     * 新增定时任务
     */
    @PostMapping
    public Result add(@RequestBody SysJob job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return Result.fail("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return Result.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi://'调用");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_LDAP)) {
            return Result.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap://'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return Result.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)//'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return Result.fail("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        }
        return Result.succ(jobService.insertJob(job));
    }

    /**
     * 修改定时任务
     */
    @PostMapping(value = "updateStatus")
    public Result edit(@RequestBody SysJob job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return Result.fail("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return Result.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi://'调用");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_LDAP)) {
            return Result.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap://'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return Result.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)//'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return Result.fail("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        }
        jobService.updateJob(job);
        return Result.succ("修改成功!");
    }

    /**
     * 定时任务状态修改
     */
    @PostMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysJob job) throws SchedulerException {
        SysJob newJob = jobService.getById(job.getId());
        newJob.setStatus(job.getStatus());
        return Result.succ(jobService.changeStatus(newJob));
    }

    /**
     * 定时任务立即执行一次
     */
    @PutMapping("/run")
    public Result run(@RequestBody SysJob job) throws SchedulerException {
        jobService.run(job);
        return Result.succ("执行成功");
    }

    /**
     * 删除定时任务
     */
    @PostMapping(value = "deleteJobs")
    public Result remove(@RequestBody SysJobDto sysJobDto) throws SchedulerException, TaskException {

            jobService.deleteJobByIds(sysJobDto.getIds().toArray((new String[0])));

        return Result.succ("删除成功");
    }
}
